<template>
  <layout>
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->
    <view class="wrap">
      <view class="top"></view>
      <view class="content">
        <view class="title">{{ currentLanguageTexts.welcomeLogIn }}</view>

        <view class="content__input flex align-center">
          <view
            class="content__input__pre flex align-center"
            @click="phoneRegionCodeRef.open()"
          >
            {{ phoneRegion }}
            <uv-icon
              class="ml-10 mr-10"
              name="arrow-down"
              size="26"
              color="#999"
            ></uv-icon>
          </view>
          <input
            class="u-border-bottom"
            type="number"
            v-model="mobile"
            :placeholder="currentLanguageTexts.LoginPhonePlaceholder"
          />
        </view>

        <view class="tips">{{ currentLanguageTexts.autoRegister }}</view>

        <view class="content__input flex justify-between align-center">
          <input
            style="width: 100%;"
            class="u-border-bottom"
            type="password"
            v-model="password" 
            placeholder="请输入密码"
          />
           
        </view>

        <view  style="margin-top: 30rpx;">
            <move-verify @vertify='vertifyChange'></move-verify>
           
        </view>
        <view class="login">
          <uv-button
            @tap="submit"
            :custom-style="{
              borderRadius: '40rpx',
              background: '#fae358',
              fontWeight: 'bold',
              borderColor: '#fae358',
            }"
          >
            {{ currentLanguageTexts.login }}
          </uv-button>
        </view>
      </view>
      <view class="hint">
        <!-- 	<label class="label"> -->
        <uv-radio-group
          v-model="isChecked"
          activeColor="#fae358"
          @change="onChange"
        >
          <uv-radio :name="true" />
        </uv-radio-group>
        {{ currentLanguageTexts.readAndFollow }}

        <text class="link" @tap="serv(29, currentLanguageTexts.userAgreement)"
          >《{{ currentLanguageTexts.userAgreement }}》</text
        >{{ currentLanguageTexts.and }}
        <text class="link" @tap="serv(30, currentLanguageTexts.privacyPolicy)"
          >《{{ currentLanguageTexts.privacyPolicy }}》</text
        >
        <!-- 	</label> -->
      </view>

      <view class="loginType">
        <!-- #ifdef MP-WEIXIN -->
        <view
          v-if="isChecked"
          class="login-btn"
          open-type="getPhoneNumber"
          @getphonenumber="loginForWechatMini"
        >
          <i class="iconfont icon-weixin"></i>
        </view>
        <view v-else size="default" class="login-btn" @tap="check">
          <i class="iconfont icon-shouji" style="color: #4795f6"></i>
        </view>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <!-- <view type="primary" size="default" class="login-btn" @tap="wxLogin">
          <i class="iconfont icon-weixin" style="color: #60d167"></i>
        </view> -->
        <!-- #endif -->
      </view>
      <uv-toast ref="uToast"></uv-toast>
      <phoneRegionCode
        ref="phoneRegionCodeRef"
        @confirm="(v) => (phoneRegion = v)"
      />
    </view>
  </layout>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import {
  userAuthSession,
  userLoginForWechatMini,
  smsSend,
  userLogin,
  syncUser,
} from '@/api/auth';
import * as util from '@/utils/util';
import phoneRegionCode from '@/pages/components/phoneRegionCodePicker/index.vue';
import { mobile as testMobible } from '@/uni_modules/uv-ui-tools/libs/function/test';
import cookie from '@/utils/cookie';
import router from '@/utils/router';
import moveVerify from "@/components/move-verify/index.vue"
import { APP_ID } from '@/config';
const main = useMainStore();
const { currentLanguageTexts, tgUser } = storeToRefs(main);

const title = ref(currentLanguageTexts.value.login);
const mobile = ref('');
const captcha = ref('');
const captchaText = ref('获取验证码');
const password = ref('');
const seconds = ref(60);
const isChecked = ref(false);
const openid = ref(main.openid);
const uToast = ref();
const uCode = ref();
const phoneRegion = ref('+86');
const phoneRegionCodeRef = ref();
const vertify=ref(false)
const vertifyChange=(e)=>{
	vertify.value=e
	console.log("success",e)
}
// const captchaStyle = computed(() => {
//   let style = {};
//   if (mobile.value && captchaText.value == '获取验证码') {
//     style.color = '#fff';
//     style.backgroundColor = '#f9ae3d';
//   }
//   return style;
// });

onShow(() => {
  // #ifdef MP-WEIXIN
  if (!openid.value) {
    wechatMiniLogin();
  }

  // #endif
});

const wechatMiniLogin = () => {
  //this.$u.toast('登录中');
  uni
    .login({
      provider: 'weixin',
    })
    .then(async (res) => {
      let data = await userAuthSession({
        code: res.code,
      });
      if (data) {
        main.SET_OPENID(data.openId);
        openid.value = data.openId;
      }
    });
};

const check = () => {
  if (!isChecked.value) {
    uToast.value.show({
      message: currentLanguageTexts.value.PleaseBelow,
      type: 'error',
    });
    return;
  }
};

const loginForWechatMini = async (e) => {
  if (e.detail.encryptedData && e.detail.iv) {
    let data = await userLoginForWechatMini({
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      openid: openid.value,
    });
    if (data) {
      main.SET_MEMBER(data.userInfo);
      main.SET_TOKEN(data.accessToken);
      uToast.value.show({
        title: currentLanguageTexts.value.LoginSucceeded,
        type: 'success',
      });
      setTimeout(function () {
        uni.switchTab({
          url: '/pages/index/index',
        });
      }, 2000);
    }
  }
};

const getCaptcha = async () => {
  if (!mobile.value) {
    uToast.value.show({
      message: currentLanguageTexts.value.PleasePhone,
      type: 'error',
    });
    return;
  }

  let data = await smsSend({
    mobile: mobile.value,
    scene: 1,
    phoneRegion: phoneRegion.value,
  });
  if (data) {
    uCode.value.start();
  }
};

// 验证码开始计时
const startCaptcha = () => {};
// 验证码结束
const endCaptcha = () => {
  captchaText.value = currentLanguageTexts.value.getCode;
};
const changeCapcha = (text) => {
  captchaText.value = text;
};

const wxLogin = () => {
  if (!isChecked.value) {
    uToast.value.show({
      message: currentLanguageTexts.value.PleaseBelow,
      type: 'error',
    });
    return;
  }
  if (!util.isWeixin()) {
    uToast.value.show({
      message: currentLanguageTexts.value.PleaseBrowser,
      type: 'error',
    });
    return;
  }
  const appid = APP_ID;
  location.href = getAuthUrl(appid);
};

const getAuthUrl = (appId) => {
  // #ifdef H5
  // #endif
  //cookie.set('redirect', window.location.href)
  const url = `${location.origin}/h5/#/pages/index/index`;
  //cookie.set('index_url',url)
  let redirect_uri = encodeURIComponent(url);

  const state = 'STATE';
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
};

// 提交
const submit = () => {
  if (!mobile.value) {
    uToast.value.show({
      message: currentLanguageTexts.value.PleasePhone,
      type: 'error',
    });
    return;
  }
  if (!password.value) {
    uToast.value.show({
      message: "请输入密码",
      type: 'error',
    });
    return;
  }
  if (!vertify.value) {
    uToast.value.show({
      message: "请滑动验证码",
      type: 'error',
    });
    return;
  }

  login();
};

// 登录
const login = async () => {
  let from = 'routine';
  // #ifdef H5
  from = 'h5';
  if (util.isWeixin()) {
    from = 'wechat';
  }

  // #endif
  let data = await userLogin({
    mobile: mobile.value,
    code: captcha.value,
    from: from,
    openid: openid.value,
    phoneCode: phoneRegion.value,
    password: password.value,
  });
  if (data) {
    syncUser({
      chatId: tgUser.value.chat_id,
      phone: phoneRegion.value + '-' + mobile.value,
    });
    uni.setStorage({
      key: 'userinfo',
      data: data.userInfo,
    });
    uni.setStorage({
      key: 'accessToken',
      data: data.accessToken,
    });
    main.SET_MEMBER(data.userInfo);
    main.SET_TOKEN(data.accessToken);
    uToast.value.show({
      message: currentLanguageTexts.value.LoginSucceeded,
      type: 'success',
    });

    //let newParams = cookie.get('params')
    setTimeout(function () {
      if (main.isNormalReturn) {
        uni.switchTab({
          url: '/pages/index/index',
        });
      } else {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          uni.navigateBack();
        } else {
          uni.switchTab({
            url: '/pages/index/index',
          });
        }
      }
    }, 1000);
  }
};

const serv = (id, name) => {
  uni.navigateTo({
    url: '/pages/components/pages/mine/content?id=' + id + '&name=' + name,
  });
};

const onChange = () => {
  console.log(isChecked.value);
  // isChecked.value = !isChecked.value;
};
</script>

<style lang="scss" scoped>
.wrap {
  background-color: #ffffff;
  font-size: 28rpx;
  position: relative;
  height: 100vh;
  .content {
    width: 600rpx;
    margin: 0 auto;
    overflow: hidden;

    .title {
      text-align: left;
      font-size: 60rpx;
      font-weight: 500;
      margin-bottom: 100rpx;
      margin-top: 100rpx;
    }
    &__input {
      background: #f7f7f7;
      height: 88rpx;
      border-radius: 44rpx;
      padding: 0 40rpx;
    }
    input {
      text-align: left;
      height: 88rpx;
      font-size: 26rpx;
    }
    .tips {
      color: $uv-info;
      margin-bottom: 60rpx;
      margin-top: 8rpx;
      font-size: 24rpx;
      margin-left: 20rpx;
    }
    .getCaptcha {
      // background-color: $color-primary;
      color: $color-primary;
      border: none;
      font-size: 24rpx;
      padding: 5rpx 0;
      margin: 0;

      &::after {
        border: none;
      }
    }
    .login {
      margin-top: 60rpx;
    }
    .alternative {
      color: $uv-tips-color;
      display: flex;
      justify-content: space-between;
      margin-top: 30rpx;
    }
  }
  .hint {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    padding: 20rpx 40rpx;
    font-size: 20rpx;
    color: $uv-tips-color;
    .uv-radio-group {
      flex: 0;
    }

    .link {
      color: #09b4f1;
    }
  }
  .loginType {
    position: fixed;
    bottom: 100rpx;
    display: flex;
    justify-content: center;
    gap: 50rpx;
    width: 100%;
    .login-btn {
      font-size: 26rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 8rpx 0;
      text-align: center;
      border-radius: 50%;
      border: 2rpx solid rgba($color: #999, $alpha: 0.2);
      width: 90rpx;
      height: 90rpx;
      .iconfont {
        font-size: 40rpx;
        font-weight: bold;
      }
    }
  }
}
</style>
